#!/usr/bin/env python3
"""
Convert points data from sample_post.json format to sample_pose_data.json format
"""

import json
import re
from typing import List, Dict, Any

def parse_points_string(points_str: str) -> List[Dict[str, float]]:
    """
    Parse points string like "[{x=404,y=215},{x=416,y=208},...]" 
    into list of dictionaries with x, y coordinates
    """
    # Remove outer brackets
    points_str = points_str.strip('[]')
    
    # Split by comma and parse each point
    points = []
    for point_str in points_str.split('},{'):
        # Clean up the point string
        point_str = point_str.strip('{}')
        
        # Extract x and y values using regex
        x_match = re.search(r'x=([\d.]+)', point_str)
        y_match = re.search(r'y=([\d.]+)', point_str)
        
        if x_match and y_match:
            x = float(x_match.group(1))
            y = float(y_match.group(1))
            points.append({"x": x, "y": y, "confidence": 0.9})  # Default confidence
    
    return points

def convert_to_pose_data_format(points: List[Dict[str, float]], timestamp: int, frame_id: int = 1) -> Dict[str, Any]:
    """
    Convert points to the pose_data format
    """
    return {
        "pose_data": {
            "keypoints": points,
            "timestamp": timestamp,
            "frame_id": frame_id
        }
    }

def main():
    # Read the sample_post.json file
    with open('sample_post.json', 'r', encoding='utf-8') as f:
        post_data = json.load(f)
    
    # Process each item in the data
    converted_data = []
    
    for i, item in enumerate(post_data['data']['items']):
        points_str = item['points']
        timestamp = item['timestamp']
        
        # Parse the points string
        points = parse_points_string(points_str)
        
        # Convert to pose_data format
        pose_data = convert_to_pose_data_format(points, timestamp, i + 1)
        converted_data.append(pose_data)
    
    # Save the first few converted items as examples
    for i, pose_data in enumerate(converted_data[:5]):  # Save first 5 as examples
        filename = f'converted_pose_data_{i+1}.json'
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(pose_data, f, indent=2, ensure_ascii=False)
        print(f"Saved {filename}")
    
    # Also save all converted data in one file
    with open('all_converted_pose_data.json', 'w', encoding='utf-8') as f:
        json.dump(converted_data, f, indent=2, ensure_ascii=False)
    print(f"Saved all_converted_pose_data.json with {len(converted_data)} pose data entries")

if __name__ == "__main__":
    main() 